package qj.tool.gae;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import qj.util.funct.F0;
import qj.util.funct.Fs;

public class Page<A> extends Paging<A> {
	public int from = 0;
	F0<List<A>> cacheListF = Fs.invokeOnce(new F0<List<A>>() {public List<A> e() {
		return listF.e(from, pageSize);
	}});

	public List<A> getList() {
		return cacheListF.e();
	}
	
	public String nav(HttpServletRequest request) {
		int currentPage = from / pageSize;
		String query = request.getQueryString();
		return 
				"<a href=\"?" + pUrl("first",query) + "\">First</a> " +
				(currentPage > 1 ? "<a href=\"?" + pUrl(currentPage - 2,query) + "\">" + (currentPage - 2) + "</a> " : "") +
				(currentPage > 0 ? "<a href=\"?" + pUrl(currentPage - 1,query) + "\">" + (currentPage - 1) + "</a> " : "") +
				" " + currentPage + " " +
				"<a href=\"?" + pUrl(currentPage + 1,query) + "\">" + (currentPage + 1) + "</a> " +
				"<a href=\"?" + pUrl(currentPage + 2,query) + "\">" + (currentPage + 2) + "</a> " +
				"<a href=\"?" + pUrl("last",query) + "\">Last</a> ";
	}

	private String pUrl(Object page, String query) {
		if (query==null) {
			return pageParam + "=" + page;
		}
		Matcher matcher = Pattern.compile("(^|&)" + pageParam + "=.+?($|&)").matcher(query);
		if (matcher.find()) {
			return matcher.replaceAll("$1" + pageParam + "=" + page + "$2");
		} else {
			return query + "&" + pageParam + "=" + page;
		}
	}
}
